package com.example.authority.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.authority.annotations.ClearPerms;
import com.example.authority.common.Result;

import com.example.authority.entity.*;
import com.example.authority.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @program: authority-hm-0.0.1
 * @ClassName:CartController
 * @description: CartController前端控制器
 * @author:dyy
 * @Version 3.0
 **/
@Tag(name = "购物车列表 前端控制器")
@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private CartService cartService;
    @Resource
    private UserService userService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private OrderService orderService;
    @Resource
    private AddressService addressService;
    /**
     * 新增
     *
     * @param cart
     * @return
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result save(@RequestBody Cart cart) {
        cart.setName(userService.getUserInfo().getUsername());
        cart.setTime(DateUtil.now());
        return Result.success(cartService.save(cart));
    }

    /**
     * 修改
     *
     * @param cart
     * @return
     */
    @Operation(summary = "修改")
    @PutMapping("/{id}")
    public Result update(@PathVariable Long id, @RequestBody Cart cart) {
        return Result.success(cartService.updateById(cart));
    }
    @Operation(summary = "支付")
    @PutMapping("/apply/{ids}/{aid}")
    @ClearPerms
    public Result apply(@PathVariable Long[] ids, @PathVariable Long aid) {
        User user=userService.getUserInfo();
        Address address = new Address();
        if (aid == 0) {
            address = addressService.getOne(new LambdaQueryWrapper<Address>().eq(Address::getIsDefault, 1).eq(Address::getUsername, user.getUsername()));
        } else {
            address = addressService.getById(aid);
        }
        double totalPrice = 0;


//        生成订单
        for (Long id : Arrays.asList(ids)) {
            Cart cart = cartService.getById(id);
            Goods goods = goodsService.getById(cart.getGid());
            totalPrice+=goods.getPrice()*cart.getScount();
            if (goods.getIsShow()==0){
                throw new RuntimeException("存在商品下架，无法下单！");
            }
            if (cart.getScount()-goods.getStore()>0){
                throw new RuntimeException("库存不足！");
            }
        }
        if (totalPrice -user.getBalance()>=0) {
            throw new RuntimeException("账户余额不足，请充值！");
        }
        for (Long id : Arrays.asList(ids)) {
            Cart cart = cartService.getById(id);
            Goods goods = goodsService.getById(cart.getGid());
            goods.setSales(goods.getSales()+cart.getScount());
            Order order=new Order();
            order.setUsername(userService.getUserInfo().getUsername());
            order.setGid(cart.getGid());
            order.setScount(cart.getScount());
            order.setTotal(goods.getPrice()*cart.getScount());
            order.setGoods(JSONUtil.toJsonStr(goods));
            // 生成唯一ID
            String uniqueId = IdUtil.randomUUID();
            order.setStatu(2);

            // 获取当前日期和时间
            String currentDate = DateUtil.today();
            String currentTime = DateUtil.now();

            // 格式化日期时间
            String formattedDateTime = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");

            // 组合日期时间和唯一ID
            String orderId = formattedDateTime + "-" + uniqueId.substring(0, 6).toUpperCase();
            order.setName(orderId);
            order.setAid(address.getId());
            order.setAddress(JSONUtil.toJsonStr(address));
            orderService.save(order);
            goodsService.saveOrUpdate(goods);
        }
        cartService.removeByIds(Arrays.asList(ids));
        return Result.success();
    }
    /**
     * 查询所有Cart
     *
     * @return
     */
    @Operation(summary = "查询所有Cart")
    @GetMapping
    public Result findAll() {
        return Result.success(cartService.list());
    }

    /**
     * 获取单个
     *
     * @param id
     * @return
     */
    @Operation(summary = "获取单个")
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(cartService.getById(id));
    }

    /**
     * 分页显示
     *
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Operation(summary = "分页显示")
    @GetMapping("/page")
    public Result findPage(
            @RequestParam(defaultValue = "") String name,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();

        queryWrapper.like("name", userService.getUserInfo().getUsername());

        queryWrapper.orderByDesc("id");
        Page<Cart> page = cartService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Cart> records = page.getRecords();
        for (Cart cart : records) {
            Goods goods = goodsService.getById(cart.getGid());
            if (goods != null) {
                cart.setGoods(goods);
            }
        }
        page.setRecords(records);
        return Result.success(page);
    }

    /**
     * 单个删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "单个删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(cartService.removeById(id));
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Operation(summary = "批量删除")
    @DeleteMapping("/batch/{ids}")
    @Transactional
    public Result deleteByIds(@PathVariable String[] ids) {
        return Result.success(cartService.removeByIds(Arrays.asList(ids)));
    }

    @Operation(summary = "批量获取")
    @GetMapping("/batch/{ids}")
    @Transactional
    public Result GetByIds(@PathVariable String[] ids) {

        List<Cart> carts = new ArrayList<>();
        for (String id : ids) {
            Cart cart = cartService.getById(Long.parseLong(id));
            carts.add(cart);
        }
        return Result.success(carts);
    }

    /**
     * 批量导出
     * 使用的技术为alibaba下面的easyexcel
     * 写数据
     *
     * @param ids
     * @return
     */
    @Operation(summary = "批量导出")
    @GetMapping("/batch/export/{ids}")
    public void exportByIds(@PathVariable String[] ids, HttpServletResponse response) throws IOException {

        List<Cart> list = cartService.listByIds(Arrays.asList(ids));
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("cart导出数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Cart.class).sheet("sheel1").doWrite(list);

    }

    /**
     * 批量导入
     * 使用的技术为alibaba下面的easyexcel
     * 读数据
     *
     * @param
     */
    @Operation(summary = "批量导入")
    @PostMapping("/batch/upload")
    public Result writeExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Cart.class, new PageReadListener<Cart>(dataList -> {
            dataList.forEach(entity -> cartService.save(entity.toBuilder().id(null).build()));
        })).sheet().doRead();
        return Result.success();
    }

}